﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MakeItWeb.Framework;

namespace AllNations.UI
{
    public partial class DailyWord : MakeItWebPage, IDynamicPage
    {
        private MakeItWeb.Framework.DailyWord _SelectedDailyWord;
        private MakeItWeb.Framework.DailyWord _CurrentDailyWord;

        public MakeItWeb.Framework.DailyWord SelectedDailyWord
        {
            get 
            {
                if (string.IsNullOrEmpty(hidSelectedDailyWordId.Value))
                    return null;

                if (_SelectedDailyWord == null)
                    _SelectedDailyWord = MakeItWeb.Framework.DailyWord.GetDailyWord(new Guid(hidSelectedDailyWordId.Value));

                return _SelectedDailyWord; 
            }
        }

        public MakeItWeb.Framework.DailyWord CurrentDailyWord
        {
            get
            {
                if (_CurrentDailyWord == null)
                    _CurrentDailyWord = MakeItWeb.Framework.DailyWord.GetCurrentDailyWord(CurrentHtmlPage.HtmlPageId);

                return _CurrentDailyWord;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ViewTabs.Tabs.FindTabByText("Administrator").Visible = IsPageAdministrator();
            }
            lblUpdateStatus.Text = string.Empty;
            lblSaveUserInputStatus.Text = string.Empty;
        }

        protected void rblChoices_DataBound(object sender, EventArgs e)
        {
            var rbl = sender as RadioButtonList;
            var q = (rbl.Parent as RepeaterItem).DataItem as DailyWordMultipleChoicesQuestion;
            var a = CurrentDailyWord.UserStatus.Answers.FirstOrDefault(i => i.DailywordQuestionId == q.DailywordQuestionId);
            if (a != null)
            {
                rbl.SelectedValue = a.AnswerTxt;
                //rbl.Enabled = !CurrentDailyWord.UserStatus.SubmittedInd;
                if (CurrentDailyWord.UserStatus.SubmittedInd)
                {
                    // get the correct answer
                    var userAnswer = rbl.Items.FindByValue(a.AnswerTxt);
                    if (userAnswer != null && q.IsCorrectAnswer(int.Parse(a.AnswerTxt)))
                    {
                        userAnswer.Text += " &nbsp; <span style='color: Green'>(Correct)</span>";
                    }
                    else
                    {
                        if (userAnswer != null)
                            userAnswer.Text += " &nbsp; <span style='color: Red'>(Wrong)</span>";

                        var correctAnswer = rbl.Items.FindByValue(q.CorrectAnswer.ToString());
                        if (correctAnswer != null)
                        {
                            correctAnswer.Text += " &nbsp; <span style='color: Green; font-weight: bold'><= This is correct answer.</span>";
                        }
                    }
                }
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (PageViews.SelectedIndex == CurrentWeekView.Index)
            {
                CurrentDailywordView.ActiveViewIndex = CurrentDailyWord == null ? 0 : 1;
                if (CurrentDailywordView.ActiveViewIndex == 1)
                {
                    var dw = CurrentDailyWord;
                    lblCurrentWeekTitle.Text = string.Format("Week #{0}: {1}&nbsp;-&nbsp;{2}",
                        dw.WeeknumId,
                        dw.WeekStart.ToShortDateString(),
                        dw.WeekEnd.ToShortDateString());

                    lblDate1.Text = dw.WeekStart.ToShortDateString();
                    lblDate1.Font.Bold = DateTime.Now.Day == dw.WeekStart.Day;
                    lblTitle1.Font.Bold = lblDate1.Font.Bold;
                    lblDate2.Text = dw.WeekStart.AddDays(1).ToShortDateString();
                    lblDate2.Font.Bold = DateTime.Now.Day == dw.WeekStart.AddDays(1).Day;
                    lblTitle2.Font.Bold = lblDate2.Font.Bold;
                    lblDate3.Text = dw.WeekStart.AddDays(2).ToShortDateString();
                    lblDate3.Font.Bold = DateTime.Now.Day == dw.WeekStart.AddDays(2).Day;
                    lblTitle3.Font.Bold = lblDate3.Font.Bold;
                    lblDate4.Text = dw.WeekStart.AddDays(3).ToShortDateString();
                    lblDate4.Font.Bold = DateTime.Now.Day == dw.WeekStart.AddDays(3).Day;
                    lblTitle4.Font.Bold = lblDate4.Font.Bold;
                    lblDate5.Text = dw.WeekStart.AddDays(4).ToShortDateString();
                    lblDate5.Font.Bold = DateTime.Now.Day == dw.WeekStart.AddDays(4).Day;
                    lblTitle5.Font.Bold = lblDate5.Font.Bold;
                    lblDate6.Text = dw.WeekStart.AddDays(5).ToShortDateString();
                    lblDate6.Font.Bold = DateTime.Now.Day == dw.WeekStart.AddDays(5).Day;
                    lblTitle6.Font.Bold = lblDate6.Font.Bold;
                    lblDate7.Text = dw.WeekStart.AddDays(6).ToShortDateString();
                    lblDate7.Font.Bold = DateTime.Now.Day == dw.WeekStart.AddDays(6).Day;
                    lblTitle7.Font.Bold = lblDate7.Font.Bold;
                    lblTitle1.Text = dw.AssignmentMondayTxt;
                    lblTitle2.Text = dw.AssignmentTuesdayTxt;
                    lblTitle3.Text = dw.AssignmentWednesdayTxt;
                    lblTitle4.Text = dw.AssignmentThursdayTxt;
                    lblTitle5.Text = dw.AssignmentFridayTxt;
                    lblTitle6.Text = dw.AssignmentSaturdayTxt;
                    lblTitle7.Text = dw.AssignmentSundayTxt;

                    rptCurrentQuestions.DataSource = dw.Questions;
                    rptCurrentQuestions.DataBind();

                    panelScore.Visible = dw.UserStatus.SubmittedInd;
                    if (panelScore.Visible)
                        lblScore.Text = string.Format("{0}/{1}", dw.UserStatus.ScoreNum, dw.UserStatus.PerfectScoreNum);
                    txtReflection.Text = dw.UserStatus.ReflectionTxt;
                    txtReflection.ReadOnly = dw.UserStatus.SubmittedInd;
                    if (dw.UserStatus.SubmittedInd)
                        rblReadFaithfully.SelectedValue = dw.UserStatus.ReadInd ? "1" : "0";
                    btSave.Visible = !dw.UserStatus.SubmittedInd && User.Identity.IsAuthenticated;
                    btSubmit.Visible = !dw.UserStatus.SubmittedInd;
                }
            }
            else if (PageViews.SelectedIndex == PreviousWeeksView.Index)
            {
                var dw = MakeItWeb.Framework.DailyWord.ListPreviousDailyWord(CurrentHtmlPage.HtmlPageId);
                var publishedDw = from i in dw
                                  where i.PublishedInd == true
                                  select i;
                rptPreviousDailyWord.DataSource = publishedDw.ToArray();
                rptPreviousDailyWord.DataBind();
            }
            else if (PageViews.SelectedIndex == AdminViews.Index)
            {
                gridAllDailyWords.DataSource = MakeItWeb.Framework.DailyWord.ListDailyWord(CurrentHtmlPage.HtmlPageId);
                gridAllDailyWords.DataBind();

                if (EditorViews.SelectedIndex == EditView.Index)
                {

                    rptQuestions.DataSource = SelectedDailyWord.Questions;
                    rptQuestions.DataBind();
                }
            }
        }

        protected void btSave_Click(object sender, EventArgs e)
        {
            bool bRebind = ScrapeAndSaveAnswers();
            if (bRebind)
                _CurrentDailyWord.UserStatus.Reset();

            lblSaveUserInputStatus.Text = string.Format("저장 되었습니다. {0}", DateTime.Now.ToString());
        }

        private bool ScrapeAndSaveAnswers()
        {
            var dw = CurrentDailyWord;
            bool bRebind = false;

            foreach (RepeaterItem item in rptCurrentQuestions.Items)
            {
                var rbl = item.FindControl("rblChoices") as RadioButtonList;
                var hidId = item.FindControl("hidDailywordQuestionId") as HiddenField;
                var id = hidId != null ? new Guid(hidId.Value) : Guid.Empty;
                if (rbl != null && rbl.SelectedIndex != -1)
                {
                    var q = dw.Questions.FirstOrDefault(i => i.DailywordQuestionId == id);
                    int iAnswer = int.Parse(rbl.SelectedValue);
                    bool bIsCorrect = q.IsCorrectAnswer(iAnswer);
                    var userAnswer = dw.UserStatus.Answers.FirstOrDefault(i => i.DailywordQuestionId == id);
                    if (userAnswer == null)
                        userAnswer = new DailyWordAnswer(q.DailywordQuestionId, dw.UserStatus.DailywordStatusId);

                    userAnswer.AnswerTxt = iAnswer.ToString();
                    userAnswer.CorrectInd = bIsCorrect;
                    userAnswer.Save();

                    bRebind = true;
                }
            }
            dw.UserStatus.ReadInd = rblReadFaithfully.SelectedValue == "1";
            dw.UserStatus.ReflectionTxt = txtReflection.Text.Trim();
            dw.UserStatus.Save();
            return bRebind;
        }

        protected void btSubmit_Click(object sender, EventArgs e)
        {
            bool bRebind = ScrapeAndSaveAnswers();
            if (bRebind)
            {
                _CurrentDailyWord.UserStatus.Reset();
                _CurrentDailyWord.UserStatus.SubmittedInd = true;
                _CurrentDailyWord.UserStatus.SubmittedDttm = DateTime.Now;
                _CurrentDailyWord.UserStatus.PerfectScoreNum = _CurrentDailyWord.Questions.Count();
                _CurrentDailyWord.UserStatus.ScoreNum = _CurrentDailyWord.UserStatus.Answers.Where(i => i.CorrectInd).Count();
                _CurrentDailyWord.UserStatus.Save();
            }

            lblSaveUserInputStatus.Text = string.Format("제출 되었습니다. {0}", DateTime.Now.ToString());
        }

        protected void lnkDeleteQuestion_Click(object sender, EventArgs e)
        {
            Guid guidDailywordQuestionId = new Guid((sender as LinkButton).CommandArgument);
            MakeItWeb.Framework.DailyWordQuestion.DeleteDailywordQuestion(guidDailywordQuestionId);
        }

        protected void btSaveNewWeek_Click(object sender, EventArgs e)
        {
            var dw = new MakeItWeb.Framework.DailyWord(CurrentHtmlPage.HtmlPageId);
            dw.WeeknumId = int.Parse(txtWeeknumId.Text.Trim());
            dw.WeekStart = rdpWeekStart.SelectedDate.Value;
            dw.WeekEnd = rdpWeekStart.SelectedDate.Value.AddDays(7);
            dw.AssignmentMondayTxt = txtMonday.Text.Trim();
            dw.AssignmentTuesdayTxt = txtTuesday.Text.Trim();
            dw.AssignmentWednesdayTxt = txtWednesday.Text.Trim();
            dw.AssignmentThursdayTxt = txtThursday.Text.Trim();
            dw.AssignmentFridayTxt = txtFriday.Text.Trim();
            dw.AssignmentSaturdayTxt = txtSaturday.Text.Trim();
            dw.AssignmentSundayTxt = txtSunday.Text.Trim();
            dw.Save();

            txtWeeknumId.Text = string.Empty;
            rdpWeekStart.SelectedDate = null;
            txtMonday.Text = string.Empty;
            txtTuesday.Text = string.Empty;
            txtWednesday.Text = string.Empty;
            txtThursday.Text = string.Empty;
            txtFriday.Text = string.Empty;
            txtSaturday.Text = string.Empty;
            txtSunday.Text = string.Empty;
        }

        protected void lnkPublish_Click(object sender, EventArgs e)
        {
            var dw = MakeItWeb.Framework.DailyWord.GetDailyWord(new Guid((sender as LinkButton).CommandArgument));
            dw.PublishedInd = true;
            dw.Save();
        }

        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            MakeItWeb.Framework.DailyWord.DeleteDailyWord(new Guid((sender as LinkButton).CommandArgument));
        }

        protected void lnkEdit_Click(object sender, EventArgs e)
        {
            EditorViews.SelectedIndex = EditView.Index;
            Guid guidDailyWordId = new Guid((sender as LinkButton).CommandArgument);
            hidSelectedDailyWordId.Value = guidDailyWordId.ToString();
            var dw = MakeItWeb.Framework.DailyWord.GetDailyWord(guidDailyWordId);
            lblWeekNumId.Text = string.Format("Week #{0}: {1}&nbsp;-&nbsp;{2}",
                dw.WeeknumId,
                dw.WeekStart.ToShortDateString(),
                dw.WeekEnd.ToShortDateString());
            lblMondayDate.Text = string.Format("{0} {1}", dw.WeekStart.Day, dw.WeekStart.DayOfWeek.ToString().Substring(0, 2));
            txtMondayUpd.Text = dw.AssignmentMondayTxt;
            lblTuesdayDate.Text = string.Format("{0} {1}", dw.WeekStart.AddDays(1).Day, dw.WeekStart.AddDays(1).DayOfWeek.ToString().Substring(0, 2));
            txtTuesdayUpd.Text = dw.AssignmentTuesdayTxt;
            lblWednesdayDate.Text = string.Format("{0} {1}", dw.WeekStart.AddDays(2).Day, dw.WeekStart.AddDays(2).DayOfWeek.ToString().Substring(0, 2));
            txtWednesdayUpd.Text = dw.AssignmentWednesdayTxt;
            lblThursdayDate.Text = string.Format("{0} {1}", dw.WeekStart.AddDays(3).Day, dw.WeekStart.AddDays(3).DayOfWeek.ToString().Substring(0, 2));
            txtThursdayUpd.Text = dw.AssignmentThursdayTxt;
            lblFridayDate.Text = string.Format("{0} {1}", dw.WeekStart.AddDays(4).Day, dw.WeekStart.AddDays(4).DayOfWeek.ToString().Substring(0, 2));
            txtFridayUpd.Text = dw.AssignmentFridayTxt;
            lblSaturdayDate.Text = string.Format("{0} {1}", dw.WeekStart.AddDays(5).Day, dw.WeekStart.AddDays(5).DayOfWeek.ToString().Substring(0, 2));
            txtSaturdayUpd.Text = dw.AssignmentSaturdayTxt;
            lblSundayDate.Text = string.Format("{0} {1}", dw.WeekStart.AddDays(6).Day, dw.WeekStart.AddDays(6).DayOfWeek.ToString().Substring(0, 2));
            txtSundayUpd.Text = dw.AssignmentSundayTxt;
        }

        protected void btSaveAssignments_Click(object sender, EventArgs e)
        {
            Guid guidDailyWordId = new Guid(hidSelectedDailyWordId.Value);
            var dw = MakeItWeb.Framework.DailyWord.GetDailyWord(guidDailyWordId);
            dw.AssignmentMondayTxt = txtMondayUpd.Text.Trim();
            dw.AssignmentTuesdayTxt = txtTuesdayUpd.Text.Trim();
            dw.AssignmentWednesdayTxt = txtWednesdayUpd.Text.Trim();
            dw.AssignmentThursdayTxt = txtThursdayUpd.Text.Trim();
            dw.AssignmentFridayTxt = txtFridayUpd.Text.Trim();
            dw.AssignmentSaturdayTxt = txtSaturdayUpd.Text.Trim();
            dw.AssignmentSundayTxt = txtSundayUpd.Text.Trim();
            dw.Save();

            lblUpdateStatus.Text = string.Format("Assignments are updated successfully on {0}", DateTime.Now.ToString());
        }

        protected void btBackToListFromEditView_Click(object sender, EventArgs e)
        {
            EditorViews.SelectedIndex = ListView.Index;
            hidSelectedDailyWordId.Value = string.Empty;
        }

        protected void btSaveQuestion_Click(object sender, EventArgs e)
        {
            var dw = MakeItWeb.Framework.DailyWord.GetDailyWord(new Guid(hidSelectedDailyWordId.Value));
            dw.AddQuestion(
                int.Parse(txtQuestionNum.Text),
                txtQuestionTxt.Text.Trim(),
                txtChoice1.Text.Trim(),
                txtChoice2.Text.Trim(),
                txtChoice3.Text.Trim(),
                txtChoice4.Text.Trim(),
                int.Parse(txtCorrectAnswer.Text));

            txtQuestionNum.Text = string.Empty;
            txtQuestionTxt.Text = string.Empty;
            txtChoice1.Text = string.Empty;
            txtChoice2.Text = string.Empty;
            txtChoice3.Text = string.Empty;
            txtChoice4.Text = string.Empty;
            txtCorrectAnswer.Text = string.Empty;
        }

        #region IDynamicPage implementation

        string IDynamicPage.PageTypeName
        {
            get { return "DailyWord"; }
        }

        string IDynamicPage.GetPageConfigurationControl()
        {
            return string.Empty;
        }

        #endregion
    }
}